<template>
	<view>
		<view class="confirm-order">
			<view class="confirm-con">
				<!-- 商品信息 -->
				<view class="goods contain">
					<view class="lease-goods">
						<lease-order-goods :image="goods.image">
							<template #name>{{ goods.goods_name }}</template>
							<template #specs>
								{{ goods.name }}，
								{{goods.Identifier}}
							</template>
							<template #price>
								<price :content="goods.price" mainSize="38rpx" minorSize="24rpx" color="#FF2C3C"
									:isPrefix="true" :isSuffix="true" />
								<text>（x{{ goods.day }}天）</text>
							</template>
						</lease-order-goods>
					</view>
				</view>

				<!-- 分期费用明细 -->
				<template v-if="type=='continue'">
					<view class="periods-price contain">
						<view class="periods-price-item">
							<view class="lighter periods-price-row row-between">
								<view>本期租金</view>
								<view style="color: #FF2C3C;">
									¥{{ totalPrice }}</view>
							</view>
							<view class="lighter periods-price-row row-between">
								<view>租期</view>
								<view>{{ orderInfo.data.last.day}}天</view>
							</view>
						</view>
					</view>
					<view class="periods-price contain">
						<view class="periods-price-item">
							<view class="lighter periods-price-row row-between">
								<view>下期租金</view>
								<view style="color: #FF2C3C;">
									¥{{ totalPrice2 }}</view>
							</view>
							<view class="lighter periods-price-row row-between">
								<view>租期</view>
								<view>{{ orderInfo.data.now.day}}天</view>
							</view>
						</view>
					</view>
				</template>
				<view v-else class="periods-price contain">
					<view class="periods-price-item">
						<view class="lighter periods-price-row row-between">
							<view>总租金</view>
							<view style="color: #FF2C3C;">
								¥{{ totalPrice }}</view>
						</view>
						<view class="lighter periods-price-row row-between">
							<view>商品租金</view>
							<view>{{ orderInfo.lists.money  }}</view>
						</view>
						<view class="lighter periods-price-row row-between">
							<view>违约租金</view>
							<view style="color: #FF2C3C;">{{ orderInfo.lists.weiyue }}</view>
						</view>
						<view class="lighter periods-price-row row-between">
							<view>租期</view>
							<view>{{ goods.day}}</view>
						</view>
						<view class="lighter periods-price-row row-between">
							<view>押金</view>
							<view>¥{{ goods.first_pay_amount }}</view>
						</view>
					</view>
				</view>

				<!-- 优惠券 -->
				<view v-if="couponList&&couponList.length>0" class="contain" style="padding: 20rpx;"
					@tap="couponSelectShow=true">
					<view class="row-between">
						<view>
							优惠券
						</view>
						<view>
							<text style="color: #FF2C3C;">-￥{{currCoupon?currCoupon.amount:0}}</text>
							<u-icon name="arrow-right" color="#666"></u-icon>
						</view>
					</view>
				</view>


				<!-- 支付方式 -->
				<view class="pay-way contain">
					<view class="lighter title">支付方式</view>
					<radio-group class="radio-group" @change="radioChange">
						<label v-for="(item, index) in payWayArr" :key="index" class="item row-between">
							<view class="row">
								<image class="icon-lg mr20" :src="item.icon" />
								<view class>
									<view class="balck bt10">{{item.name}}</view>
									<view class="muted xs">{{item.extra}}</view>
								</view>
							</view>
							<radio class="radio" :value="String(item.pay_way)" :checked="item.pay_way == payWay" />
						</label>
					</radio-group>
				</view>

			</view>

			<!-- 订单结算 -->
			<view class="footer bg-white fixed">
				<view class="row-between">
					<view class="all-price lg row">
						<text>合计：</text>
						<view class="ornament">
							<price :content="totalMoney" mainSize="38rpx" minorSize="30rpx" :isSuffix="false"
								:isPrefix="true" />
						</view>
					</view>
					<button class="btn br60 white" size="md" hover-class="none" @tap="onSubmitOrder">
						确认支付
					</button>
				</view>
			</view>
		</view>

		<loading-view v-if="showLoading" />

		<coupon-popup v-model="couponSelectShow" @confirm="e=>currCoupon=e" :current="currCoupon"
			:can-use-coupon-list="couponList"></coupon-popup>

		<!-- 支付密码 -->
		<set-pay-pwd ref="setPayPwd" @confirm="orderBuyFun" />
	</view>
</template>

<script>
	import {
		prepay,
		getMnpNotice,
		getAlipayPayStatus
	} from '@/api/app';
	import {
		wxpay,
		alipay
	} from '@/utils/pay'

	import {
		postReturnBill,
		postContinueLease
	} from '../../../api/user';
	import {
		payment,
	} from '@/api/lease.js'

	export default {
		data() {
			return {
				showLoading: true,
				orderInfo: {}, // 订单信息
				goods: {}, // 商品数据

				payWayArr: [], // 支付方式列表
				payWay: '', // 所选的支付方式

				couponList: [],
				couponSelectShow: false, //优惠券选择列表
				currCoupon: null, //当前优惠券

				totalPrice: 0, //合计末期
				totalPrice2: 0, //合计首期

				type: null,
				periods_id: null,
			};
		},

		computed: {
			totalMoney() {
				if (!this.currCoupon) return this.totalPrice;
				return this.totalPrice - Number(this.currCoupon.amount);
			},
		},

		methods: {
			// 选择支付方式
			radioChange(e) {
				const value = e.detail.value;
				this.payWay = value * 1;
			},

			// 微信
			getAuthMsg() {
				return new Promise(resolve => {
					getMnpNotice({
						scene: 1
					}).then(res => {
						if (res.code == 1) {
							const data = res.data;
							uni.requestSubscribeMessage({
								tmplIds: data
							});
						}
						resolve();
					});
				});
			},

			// 点击下单
			onSubmitOrder() {
				uni.showModal({
					title: '温馨提示',
					content: '是否确认下单?',
					confirmColor: '#FF2C3C',
					success: async res => {
						if (!res.confirm) return;

						// #ifdef MP-WEIXIN
						await this.getAuthMsg();
						// #endif

						if (this.payWay == 3) {
							this.$refs.setPayPwd.hasPayWord().then(res => {
								this.$refs.setPayPwd.showInputPwd();
							});
						} else {
							this.orderBuyFun();
						}
					}
				});
			},

			// 下单处理
			async orderBuyFun(password) {
				this.showLoading = true;
				if (!this.payWayArr.length) {
					this.showLoading = false;
					return this.$toast({
						title: '请联系管理员配置支付方式'
					});
				}

				const goods = this.goods;

				const submitObj = {
					action: 'submit',
					pay_way: this.payWay,
					pay_password: password,
					id: this.orderInfo.id,
					coupons_id: this.currCoupon ? this.currCoupon.id : 0
				};

				let res;
				if (this.type == 'continue') {
					submitObj.action = 'go_buy';
					submitObj.periods_id = this.periods_id;
					res = await postContinueLease(submitObj);
				} else
					res = await postReturnBill(submitObj);
				this.showLoading = false;
				const data = res.data;
				const code = res.code;
				if (code != 1) {
					uni.showToast({
						title: res.msg,
						icon: 'error'
					})
					return;
				}
				const order_id = data.order_id;
				console.log('res>>', res)
				const type = data.from;
				console.log('type>>', type)
				prepay({
					from: type,
					order_id: order_id,
					// #ifdef MP-WEIXIN
					order_source: 1,
					// #endif
				}).then(({
					code,
					data
				}) => {
					switch (code) {
						// 微信支付
						case 1:
							this.payWeChat(data, order_id);
							break;
							// 支付宝支付
						case 20001:
							this.payAliPay(data, order_id);
							break;
							// 余额支付
						case 10001:
							this.$toast({
								title: "支付成功！"
							}, {
								tab: 5,
								url: '/package_user/pages/goods_return_list/goods_return_list'
							})
							break;
					}
				}).catch(err => {
					this.$toast({
						title: '支付失败，请重试'
					});
					console.log(err);
				});
			},

			// 微信支付
			payWeChat(data, orderID) {
				wxpay(data).then(res => {
					if (res == 'success') {
						this.$toast({
							title: "支付成功！"
						}, {
							tab: 5,
							url: '/package_user/pages/goods_return_list/goods_return_list'
						})
					} else {
						this.$toast({
							title: "支付失败！"
						}, {
							tab: 5,
							url: '/package_user/pages/goods_return_list/goods_return_list'
						})
					}
				})
			},

			// 支付宝支付
			payAliPay(data, orderID) {

				// #ifdef H5
				alipay(data);
				// #endif

				// #ifdef MP-ALIPAY
				const tradeNo = data?.data?.trade_no;
				my.tradePay({
					// 调用统一收单交易创建接口（alipay.trade.create），获得返回字段支付宝交易号trade_no
					tradeNO: tradeNo,
					success: (res) => {
						getAlipayPayStatus({
							trade_no: tradeNo
						}).then(res => {
							if (res.tradeStatus == 'TRADE_SUCCESS') {
								uni.redirectTo({
									url: '/package_user/pages/goods_return_list/goods_return_list'
								});
							} else {
								uni.redirectTo({
									url: '/package_user/pages/goods_return_list/goods_return_list'
								});
							}
						});
					},
					fail: (res) => {
						uni.redirectTo({
							url: '/package_user/pages/goods_return_list/goods_return_list'
						});
					}
				});
				// #endif
			}
		},


		onLoad(options) {
			const id = options.id;
			this.type = options.type
			this.periods_id = options.periods_id
			if (this.type == 'continue') {
				// 获取付款方式
				// payment().then(res => {
				// 	if (res.code != 1) return this.$toast({
				// 		title: res.msg
				// 	});
				// 	const data = res.data;
				// 	this.payWayArr = data;
				// 	this.payWay = data.length ? data[0].pay_way : 0
				// });
				postContinueLease({
					id,
					action: 'buy',
					periods_id: this.periods_id
				}).then(res => {
					if (res != 1) this.$toast({
						title: res.msg
					});
					const data = res.data;
					this.orderInfo = data;
					this.goods = {
						...data.goods,
						goods_name: data.goods.name,
						name: data.name,
						Identifier: data.data.now.Identifier,
						price: data.data.now.day_money,
						day: data.data.now.day
					}
					this.totalPrice2 = data.data.now.amount_payable;
					this.totalPrice = data.data.now.pay_amount;
					this.couponList = data.coupon
					this.payWayArr = data.payment;
					this.payWay = this.payWayArr.length ? this.payWayArr[0].pay_way : 0
					this.showLoading = false;
				})
			} else {
				postReturnBill({
					id,
					action: 'info'
				}).then(res => {
					if (res != 1) this.$toast({
						title: res.msg
					});
					const data = res.data;
					this.payWayArr = data.goods_info.payment;
					this.payWay = this.payWayArr.length ? this.payWayArr[0].pay_way : 0;
					this.orderInfo = data;
					this.goods = data.goods_info;
					this.totalPrice = Number(data.lists.money) + Number(data.lists.weiyue)
					this.showLoading = false;
					this.couponList = data.goods_info.coupon
				})
			}
		},

	}
</script>
<style lang="scss">
	.confirm-order .confirm-con {
		overflow: hidden;
		padding: 0 20rpx calc(126rpx + 20rpx + env(safe-area-inset-bottom));
	}

	.confirm-order .img-line {
		height: 1.5px;
		width: 100%;
		display: block;
	}


	.confirm-order .coupons {
		height: 100rpx;
		padding: 0 24rpx;
	}

	.goods .title {
		padding: 22rpx 24rpx;
		border-bottom: 1px solid #F6F6F6;
	}

	.goods .all-num {
		padding: 22rpx 24rpx;
		border-bottom: 1px dotted #F6F6F6;
	}

	.lease-goods {
		padding: 24rpx 20rpx;
	}

	.confirm-order .footer {
		box-sizing: content-box;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 126rpx;
		padding-left: 20rpx;
		padding-right: 20rpx;
		padding-top: 10rpx;
		padding-bottom: env(safe-area-inset-bottom);
	}


	.confirm-order .pay-way .title {
		padding: 20rpx 24rpx;
	}

	.confirm-order .pay-way .radio-group .item {
		height: 120rpx;
		padding: 0 24rpx;
	}

	.confirm-order .price {
		padding: 28rpx 20rpx;
	}

	.confirm-order .price .item:not(:last-of-type) {
		margin-bottom: 20rpx;
	}

	.confirm-order .goods>.item,
	.confirm-order .benefit>.item {
		padding: 0 24rpx;
		height: 80rpx;
	}

	.confirm-order .btn {
		background-color: #24A3FF;
		padding: 0 50rpx;
	}

	.confirm-order .van-cell:after {
		border: none;
	}

	.goods .shop-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.pop-title {
		height: 100rpx;
		border-bottom: 1rpx solid #F2F2F2;
	}

	.pop-title .title {
		margin-left: 30rpx;
		font-size: 34rpx;
		font-weight: bold;
		line-height: 36rpx;
	}

	.periods-price {
		padding: 0 20rpx;
	}

	.periods-price-item {
		padding: 20rpx 0;
	}

	.periods-price-item:nth-child(n + 2) {
		border-top: 1px solid #E5E5E5;
	}

	.periods-price-title {
		padding: 10rpx 0;
		font-size: 30rpx;
		font-weight: 500;
		color: #333333;
	}

	.periods-price-row {
		padding: 10rpx 0;
		font-size: 26rpx;
	}

	.contain {
		background-color: white;
		border-radius: 24rpx;
		margin-top: 20rpx;
	}
</style>